﻿//*** Guidance generated code ***//
using System;
using System.Configuration;

namespace $safeprojectname$.Publishing.Configuration
{
    public class PublishingConfigurator
    {
        public virtual IPublishingProvider CreateProvider()
        {
            var config = ConfigurationManager.GetSection(Constants.SectionPublishing) as PublishingConfiguration;
            return CreateProvider(config);
        }

        public virtual IPublishingProvider CreateProvider(PublishingConfiguration config)
        {
            if (config.IsNull())
            {
                return new NullPublishingProvider();
            }
            if (config.ProviderType.IsNull())
            {
                throw new ConfigurationErrorsException("Publishing: configuration has missing provider type. See the doc for configuration.<publishing><provider>");
            }
            var type = Type.GetType(config.ProviderType);
            if (type.IsNull())
            {
                throw new ConfigurationErrorsException("Publishing: provider element does not contain correct 'type' name.");
            }

            try
            {
                var provider = Activator.CreateInstance(type) as IPublishingProvider;
                if (provider.IsNull())
                {
                    throw new ConfigurationErrorsException("Publishing: provider element 'type' contains object, which does not implement 'IPublishingProvider' interface.");
                }
                provider.Init(config.Settings);
                return provider;
            }
            catch (ConfigurationErrorsException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException("PublishingProvider config: provider type {0} could not be created. See inner exception."
                    .FormatWith(config.ProviderType)
                    , ex);
            }
        }
    }
}
